<template>
    <div>
        <li class="todo" :class="{completed:todo.done,editing:editing}">
            <div class="view">
                <input
                class="toggle"
                type="checkbox"
                :checked="todo.done"
                @change="toggleTodo(todo)"
                >
                <label
                    v-text="todo.text"
                    @dblclick="editing = true"
                ></label>
                
                <button class="destroy" @click="removeTodo(todo)"></button>
            </div>
            <input class="edit" v-focus='editing' :value="todo.text" v-show="editing" @keyup.enter="edit" @keyup.esc="cancle">
            
        </li>
    </div>
</template>

<script>
import { mapActions } from "vuex";
export default {
  props: ["todo"],
  data() {
    return {
      editing: false
    };
  },
  methods: {
    ...mapActions(["removeTodo", "toggleTodo", "editTodo"]),
    edit(e) {
      let value = e.target.value.trim();
      let { todo } = this;
      if (!value) {
        this.removeTodo(todo);
      } else if (this.editing) {
        this.editTodo({
          todo,
          value
        });
      }
      this.editing = false;
    },
    cancle(e) {
      e.target.value = this.todo.text;
      this.editing = false;
    }
  },
  directives: {
    focus(el, { value }, { context }) {
      //   console.log(binding);
      if (value) {
        // el.focus;
        context.$nextTick(() => {
          el.focus();
        });
      }
    }
  }
};
</script>

<style scoped>
</style>